<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>
        <template #right>
          <el-button 
          type="warning" 
          size="small"
          @click="$router.pash('/import')"
          >excel导入</el-button>
          <el-button type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table 
        border 
        :data="list"
        :default-sort="{prop:'timeOfEntry',order:'descending'}"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
           <el-table-column label="头像">
            <template #default="{row}">
        <img 
        v-imgerror="require('@/assets/common/bigUserHeader.png')"
        :src="row.staffPhoto" 
        alt=""
        style="width:100%"
        >
      </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable/>
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <!-- 使用作用域插槽自定义内容展示数据 -->
            <template #defaut="{ row }">
              {{ formatData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable/>
          <el-table-column label="操作" width="280">
            <template>
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
         <el-pagination
      :current-page="page"
      :page-size="size"
      layout=" prev, pager, next"
      @current-change="handleCurrentChange">
    </el-pagination>
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <addEmployees @sucess="hSuccess" @click="showData=false"/>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import addEmployees from './empDialog.vue'
import { getEmployees } from "@/api/employees";
import employeesEnum from "@/constant/employees";
// import { validUsername } from '@/utils/validate';
console.log(employeesEnum, "employeesEnum");
console.log(employeesEnum.hireType, "employeesEnum.hireType");
// const hireType = {};
// employeesEnum.hireType.forEach((item) => {
//   hireType[item.id] = item.value;
  const hireType=employeesEnum.hireType.reduce((acc,item)=>{
    acc[item.id]=item.value
    return acc
  },{})
// });
export default {
  components:{
addEmployees
  },
  data() {
    return {
      showDialog:false,
      list: [],
      page: 1,
      size: 5,
      total: 0,
    };
  },
  created() {
    this.looadEmployees();
  },
  methods: {
        exportExcel() {
      // 1. 发送到后台获取数据
      // console.log(this.list, 'listssssssssss')
      // 2. 将获取到的数据进行格式化处理， tHeaer-->[表头] ，data--->[[],[]]
      const { tHeader, data } = this.transZhKeyToExcel(this.list)
      // 3. 将格式化好的数据写入到 excel文件中');
      // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then(excel => {
        // excel指的模块对象，那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量   excel.函数名()
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    transZhKeyToExcel(list) {
      //    中引文的映射对象
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      // tHeader = ['编号','密码','手机号','姓名','入职日期',.......]

      // 1 生成表头
      const one = list[0] // unfined || 有数据
      if (!one) return
      //  Object.keys(one)---> ['correctionTime','id','password','mobile']
      const tHeader = Object.keys(one).map(enkey => {
        return mapInfo[enkey]
      })
      // tHeader  ---> ['转正日期', '部门', '聘用形式', '编号', '手机号', '密码', '头像地址', '入职日期', '姓名', '工号']
      // 2 生成表的内容data
      const data = list.map(item => {
        return Object.values(item)
      })

      return { tHeader, data }
    },
     hDel(id) {
      this.$confirm('您确定要删除该员工吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 确定实现删除
        const res = await delEmployees(id)
        if (res.code === 10000) {
          this.$message.success(res.message)
          if (this.list.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          this.loadEmployees()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 关闭弹层，重新渲染数据
    hSuccess(){
      this.total++
      const maxPage=Math.ceil(this.total / this.size)
      this.page=maxPage
this.loadEmployees()
this.showDialog=false
    },
    handleCurrentChange(val){
        this.page=val
        this.loadEmployees()
    },

    formatData(id) {
      console.log(id, "id");
      return hireType[id] || '未知'
    },
    async loadDepartments() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size });
        if (res.code !== 10000) return this.$message.error(res.message);
        this.$message.success(res.message);
        res.data.depts.shift();
        this.list = res.data.rows;
        this.total = res.data.total;
      } catch (error) {
        console.log(error);
        // this.$message.error('获取数据失败')
      }
    },
  },
};
</script>